import React, { Component } from "react";
import { Map, fromJS } from "immutable";

import { Radio } from "antd";
const RadioGroup = Radio.Group;
declare let window: any;
const { msg, xKit, BusinessDataCenter, commonComp } = window.xDllContext;
import AnimateTypeEdit from "./animateType.setting";
import { SortableContainer, SortableElement, arrayMove } from "react-sortable-hoc";
const SortableList = SortableContainer(({ items, onClickDel, replaceImg, _add }) => {
  return (
    <ul>
      {items.map((value, index) => (
        <SortableItem
          key={`item-${index}`}
          index={index}
          value={value}
          total={items.length}
          onClickDel={() => onClickDel(index)}
          replaceImg={event => replaceImg(index, event)}
        />
      ))}
      {items.length < 10 && (
        <li className="addBtn-li" onClick={_add}>
          <i style={{ fontSize: "50px" }}>+</i>
        </li>
      )}
    </ul>
  );
});
const SortableItem = SortableElement(({ total, value, onClickDel, index, replaceImg }) => (
  <li
    style={{
      position: "relative",
      zIndex: 115,
      float: "left",
      width: "100px",
      marginBottom: "10px",
      marginRight: "10px",
      background: "#f7f7f7"
    }}
  >
    <img
      style={{
        width: "100px",
        height: "122px",
        margin: "0 auto",
        display: "block",
        cursor: "move"
      }}
      src={value.content}
      alt=""
    />
    <div className="dragdrop-box-img">
      <div className="dragdrop-right-img del right-del">
        <a className="x-site-new-qIcon brand" onClick={replaceImg} />
      </div>
      {total > 1 && (
        <div className="dragdrop-right-img del right-del">
          <a className="x-site-new-qIcon del" onClick={onClickDel} />
        </div>
      )}
    </div>
  </li>
));
// 轮播最大尺寸
const MAX_SIZE = 10;
// 轮播图片选项
const sizeArray = { big: "大", default: "默认", small: "小" };
// 轮播图片建议尺寸
const sizeSuggest = { big: "750x535", default: "750x335", small: "750x235" };
// 轮播的点选项
const dotArray = { dot: "圆点", default: "默认" };

export default class SliderCommonEdit extends Component<any, any> {
  constructor(props) {
    super(props);
    this.state = {
      items: this.props.compConfig
    };
  }

  static displayName = "SliderCommonEdit";

  static defaultProps = {
    compConfig: Map()
    // imageSize: "", //1920x1300 进行压缩控制的
    // list: Immutable.List(),
  };

  render() {
    const compConfig = this.props.compConfig.get("props");
    const size = compConfig.getIn(["bottom", "style", "size"]);
    const dot = compConfig.getIn(["bottom", "style", "dot"]);
    let animateType = compConfig.getIn(["bottom", "style", "animateType"]);

    if (animateType === "default") animateType = "normal"; // 兼容老数据
    const items: any[] = fromJS(compConfig.getIn(["bottom", "items"])).toJS();
    return (
      <div className="overflowH">
        <AnimateTypeEdit activeType={animateType} onChange={this.changeAnimateType} />
        <div className="picArea">
          <p style={{ marginBottom: "10px" }}>
            轮播列表：<span style={{ fontSize: "12px", color: "#8a8a8a" }}>（最多上传10）</span>
          </p>
          {/*渲染轮播图片*/}

          <SortableList
            items={items}
            shouldCancelStart={(e: any) => e.target.classList.contains("x-site-new-qIcon")}
            onSortEnd={this.onSortEnd}
            axis="xy"
            onClickDel={this._del}
            replaceImg={this._chooseImageDialog}
            _add={this._add}
          />

          <div style={{ color: "#999", fontSize: "12px", float: "left" }}>
            建议图片尺寸：<span style={{ fontWeight: "bold" }}>1080*1312</span>
            <br />
            图片格式：JPEG、JPG、PNG、GIF，单图片大小不超过2M）
          </div>
        </div>
      </div>
    );
  }

  // 拖拽组件嵌入
  onSortEnd = ({ oldIndex, newIndex }) => {
    const { __info, compConfig } = this.props;

    if (oldIndex === newIndex) return;
    const changedData: any[] = [];
    const items = compConfig.getIn(["props", "bottom", "items"]).toJS();
    const data = arrayMove(items, oldIndex, newIndex);
    changedData.push({
      path: ["props", "bottom", "items"],
      value: fromJS(data)
    });

    if (__info) {
      changedData.push({
        path: ["__info"],
        value: this.swapInfo(oldIndex, newIndex)
      });
    }

    this.props.onMultiDataChange(changedData);
    // this._changeVal(['props', 'items'], fromJS(data));
  };

  /**
   * 交换__info数据
   * @desc  交换__info下存储位置,否则交换顺序会引起数据错乱
   * @param oldIndex  {Number}
   * @param newIndex {Number}
   */
  swapInfo(oldIndex, newIndex) {
    let { __info } = this.props;
    if (!__info) return null; // 不需要交换
    const current = ["props", "bottom", "items", newIndex, "imgHref"].join(",");
    const target = ["props", "bottom", "items", oldIndex, "imgHref"].join(",");
    console.log("测试===================" + __info);
    __info = __info.set(current, __info.get(target)).set(target, __info.get(current));
    __info = __info.filter(item => !!item); // 过滤掉undefined
    return __info;
  }

  // 改变轮播尺寸
  _changeSize = event => {
    event.preventDefault();
    this._changeVal(["props", "bottom", "style", "size"], event.target.value);
  };

  // 改变轮播点
  _changeDot = event => {
    event.preventDefault();
    this._changeVal(["props", "bottom", "style", "dot"], event.target.value);
  };

  // 改变轮播动画类型
  changeAnimateType = type => {
    this._changeVal(["props", "bottom", "style", "animateType"], type);
  };

  _changeVal = (pathArray, newVal) => {
    this.props.onDataChange(pathArray, newVal);
  };

  // 添加
  _add = () => {
    const compConfig = this.props.compConfig.get("props");
    msg.emit("edit:chooseImage", {
      changeVal: chooseImageInfo => {
        const imageSrc = chooseImageInfo.info.src;
        let newItems = compConfig.get("bottom").get("items");
        newItems = newItems.push(
          fromJS({
            content: imageSrc,
            imgHref: ""
          })
        );
        this._changeVal(["props", "bottom", "items"], newItems);
      }
    });
  };

  // 删除
  _del = index => {
    const compConfig = this.props.compConfig.get("props");
    const newItems = compConfig
      .get("bottom")
      .get("items")
      .delete(index);
    this._changeVal(["props", "bottom", "items"], newItems);
  };

  // 选择图片
  _chooseImageDialog = (index, event) => {
    const { commonUtil } = window.xSiteIntegrate;
    const compConfig = this.props.compConfig.get("props");
    const size = compConfig.getIn(["bottom", "style", "size"]);
    let currentImagePath: any[] = [];
    currentImagePath = ["props", "bottom", "items"].concat([index, "content"]);
    const currentImage = compConfig.getIn(currentImagePath);
    // const _this = this;
    const w = "1080";
    const h = "1312";

    msg.emit("edit:chooseImage", {
      otherInfo: this.props.otherInfo,
      currentVal: currentImage,
      __data_info: this.props.__info ? this.props.__info.get(currentImagePath.join(",")) : null,
      changeVal: chooseImageInfo => {
        chooseImageInfo.compressedWidth = w;
        chooseImageInfo.compressedHeight = h;
        const imageSrc = commonUtil.getPicSrc(chooseImageInfo.info.src, w, h);
        this.props._changeVal(currentImagePath, imageSrc, chooseImageInfo);
      }
    });
  };
}
